package com.yuyou.tas.lesson.service.impl;


import com.yuyou.tas.lesson.mapper.BaseSchoolMapper;
import com.yuyou.tas.lesson.mapper.LessonClassMapper;
import com.yuyou.tas.lesson.service.IBaseSchoolService;
import com.yuyou.tas.service.api.admin.entity.AuthUser;
import com.yuyou.tas.service.api.admin.service.AuthUserAPI;
import com.yuyou.tas.service.api.lesson.dto.DtoBaseSchool;
import com.yuyou.tas.service.api.lesson.entity.BaseSchool;
import com.yuyou.tas.service.api.lesson.entity.LessonClass;
import com.yuyou.tas.util.bean.LoginRedisObj;
import com.yuyou.tas.util.bean.Pagination;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.enums.admin.AuthUserEnums;
import com.yuyou.tas.util.enums.lesson.LessonBaseEnums;
import com.yuyou.tas.util.exception.BusinessException;
import com.yuyou.tas.util.tool.DefindBeanUtils;
import com.yuyou.tas.util.tool.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class BaseSchoolServiceImpl implements IBaseSchoolService {

	@Autowired
	private BaseSchoolMapper schoolMapper;

	@Autowired
	private LessonClassMapper lessonClassMapper;

	@Autowired
	private AuthUserAPI authUserAPI;

	@Autowired
	private IBaseSchoolService schoolService;

	@Override
	public int deleteByPrimaryKey(Long id){
		return schoolMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(BaseSchool record){
		record.setId(Sequence.getSequence().nextId());
		record.setValue(record.getId());
		record.setCreateTime(new Date());
		return schoolMapper.insert(record);
	}

	@Override
	public BaseSchool selectByPrimaryKey(Long id){
		return schoolMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(BaseSchool record){
		return schoolMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo addSchool(String schoolName, LoginRedisObj user,Long organId) {
		ResBoolSimpleInfo info = new ResBoolSimpleInfo();
		BaseSchool school = new BaseSchool();
		school.setId(Sequence.getSequence().nextId());
		school.setCreateTime(new Date());
		school.setAuthOrganizationId(organId);
		school.setName(schoolName);
		school.setIsStan(1);//是否标注化数据-暂缺
		school.setIsUse(LessonBaseEnums.isEnableed.enabl.getValue());
		school.setValue(school.getId());

		//获取最大code值
		Map<String, Object> condion = new HashMap<>();
		condion.put("organ_id",organId);
		condion.put("isUse","1");
		Long maxCode = schoolMapper.findMaxCode(condion);
		school.setCode(maxCode != null ? (maxCode+1)+"":"1");

		schoolMapper.insert(school);

		info.setSuccess(true);
		info.setMessage("插入成功");
		return info;
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo updateSchool(String schoolName,Long id) {
		ResBoolSimpleInfo info = new ResBoolSimpleInfo();
		BaseSchool school = new BaseSchool();
		school.setId(id);
		school.setName(schoolName);
		schoolMapper.updateByPrimaryKeySelective(school);

		info.setSuccess(true);
		info.setMessage("更新成功");
		return info;
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo delSchool(Long id) throws Exception{
		ResBoolSimpleInfo info = new ResBoolSimpleInfo();

		List<LessonClass> lcs = lessonClassMapper.selectBySchoolId(id , null);//获取该校区绑定的班级
		if(!CollectionUtils.isEmpty(lcs)){
			final List<String> existList = new ArrayList<>();
			lcs.forEach(lc -> existList.add(lc.getName()));
			throw new BusinessException("该校区已被班级：[" + String.join("，",existList) + "] 引用，更换班级校区后才可删除。");
		}

		schoolMapper.deleteByPrimaryKey(id);

		info.setSuccess(true);
		info.setMessage("删除成功");
		return info;
	}

	@Override
	public ResBoolSimpleInfo<BaseSchool> getSchoolByID(Long id) {
		BaseSchool bs = schoolMapper.selectByPrimaryKey(id);
		ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,null,bs);
		return info;
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public int findSchoolCount(Pagination<DtoBaseSchool> queryPgn) {
		return schoolMapper.findSchoolCount(queryPgn);
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public List<DtoBaseSchool> findSchoolPageList(Pagination<DtoBaseSchool> queryPgn) {
		return schoolMapper.findSchoolPageList(queryPgn);
	}

	@Override
	public BaseSchool selectByPKandOrgan(Long id, Long authOrganizationId) {
		return schoolMapper.selectByPKandOrgan(id, authOrganizationId);
	}

	@Override
	public BaseSchool selectByOrgan7OId(Long oId, Long authOrganizationId) {
		return schoolMapper.selectByOrgan7OId(oId, authOrganizationId);
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> syncSchool(List<BaseSchool> baseSchools) {		
		for(BaseSchool b:baseSchools){
			BaseSchool baseSchool=this.selectByOrgan7OId(b.getoId(),b.getAuthOrganizationId());
			BaseSchool up=new BaseSchool();
			DefindBeanUtils.copyProperties(b, up);
			if(baseSchool!=null){
				up.setIsStan(0);
				up.setId(baseSchool.getId());
				this.updateByPrimaryKeySelective(up);
			}else{
				up.setIsStan(0);
				up.setIsUse(LessonBaseEnums.isEnableed.enabl.getValue());
				//获取最大code值
				Map<String, Object> condion = new HashMap<>();
				condion.put("organ_id",b.getAuthOrganizationId());
				condion.put("isUse",LessonBaseEnums.isEnableed.enabl.getValue());
				Long maxCode = schoolMapper.findMaxCode(condion);
				up.setCode(maxCode != null ? (maxCode+1)+"":"1");
				this.insert(up);
			}
			
		}	
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	@Deprecated
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> delSchoolByOrgan7OIds(List<Long> oIds,
			Long authOrganizationId) {
		for(Long oId:oIds){
//			schoolMapper.delByOrgan7OId(oId, authOrganizationId);
		}		
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public int findTeacherSchoolCount(Pagination<DtoBaseSchool> queryPgn) {
		return schoolMapper.findTeacherSchoolCount(queryPgn);
	}

	@Override
	public List<DtoBaseSchool> findTeacherSchoolPageList(Pagination<DtoBaseSchool> queryPgn) {
		return schoolMapper.findTeacherSchoolPageList(queryPgn);
	}

	@Override
	public List<BaseSchool> getByOrganId(Long organId) {
		return schoolMapper.getByOrganId(organId);
	}

	@Override
	public List<DtoBaseSchool> selectByLimits(Pagination<DtoBaseSchool> queryPgn) {
		return schoolMapper.selectByLimits(queryPgn);
	}

	@Override
	public Integer selectByLimitsCount(Pagination<DtoBaseSchool> queryPgn) {
		return schoolMapper.selectByLimitsCount(queryPgn);
	}

	@Override
	public List<DtoBaseSchool> getUsersAllSchools(Integer tag, Long userId, Long organId, Integer userType, boolean isManager) {
		List<DtoBaseSchool> list = new ArrayList<>();
		AuthUser authUser = authUserAPI.selectById(userId);
		if(authUser == null){
			throw new BusinessException("找不到用户信息");
		}
		if(tag != null && tag == 2 && AuthUserEnums.schoolType.part.getValue() == authUser.getSchoolType()){//根据用户权限获取校区
			list = schoolService.selectAllByLimits(userId);
		}else if(isManager || tag == null || tag != 1){//非教师
			List<BaseSchool> schools = schoolMapper.getByOrganId(organId);
			if(schools != null){
				for (BaseSchool baseSchool:
						schools) {
					DtoBaseSchool dtoBaseSchool = new DtoBaseSchool();
					dtoBaseSchool.setCreateTime(baseSchool.getCreateTime());
					dtoBaseSchool.setId(baseSchool.getId());
					dtoBaseSchool.setName(baseSchool.getName());
					list.add(dtoBaseSchool);
				}
			}
		}else{//教师角色
			list = schoolService.findTeacherSchools(userId);
		}
		return list;
	}


	@Override
	public List<DtoBaseSchool> selectAllByLimits(Long userId) {
		return schoolMapper.selectAllByLimits(userId);
	}

	@Override
	public List<DtoBaseSchool> findTeacherSchools(Long userId){
		return schoolMapper.findTeacherSchools(userId);
	}
}